package com.easychat.controller;

import com.easychat.annotation.GlobalInterceptor;
import com.easychat.entity.config.AppConfig;
import com.easychat.entity.constants.Constants;
import com.easychat.entity.enums.AppUpdateFileTypeEnum;
import com.easychat.entity.po.AppUpdate;
import com.easychat.entity.query.AppUpdateQuery;
import com.easychat.entity.vo.AppUpdateVo;
import com.easychat.entity.vo.PaginationResultVO;
import com.easychat.entity.vo.ResponseVO;
import com.easychat.service.AppUpdateService;
import com.easychat.utils.StringTools;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

/**
 * @Author Dongdong
 * @注释 检测更新
 */
@RestController("updateController")
@RequestMapping("/update")
public class updateController extends ABaseController {

    @Resource
    private AppUpdateService appUpdateService;
    @Resource
    private AppConfig appConfig;

    @RequestMapping("/checkVersion")
    @GlobalInterceptor
    //由于每次启动客户端也会调用这个接口检测是否是最新版本，所以appVersion 可以为空
    public ResponseVO checkVersion(String appVersion, String uid) {

        if (StringTools.isEmpty(appVersion)) {
            return getSuccessResponseVO(null);
        }
        AppUpdate appUpdate = appUpdateService.getLatestUpdate(appVersion, uid);
        //如果没有更新，则返回null
        if (appUpdate == null) {
            return getSuccessResponseVO(null);
        }

        AppUpdateVo appUpdateVo = new AppUpdateVo();

        BeanUtils.copyProperties(appUpdate, appUpdateVo);

        //如果是本地文件，则返回文件大小
        if (AppUpdateFileTypeEnum.LOCAL.getType().equals(appUpdate.getFileType())){
            File file = new File(appConfig.getProjectFolder()+ Constants.APP_UPDATE_FOLDER+appUpdate.getId()+Constants.APP_EXE_SUFFIX);
            appUpdateVo.setSize(file.length());
        }else {
            //如果是远程文件，则返回size 为0
            appUpdateVo.setSize(0l);
        }
        //下载时的文件名
        String fileName = Constants.FILE_NAME+appUpdate.getVersion()+Constants.APP_EXE_SUFFIX;
        appUpdateVo.setFileName(fileName);
        appUpdateVo.setUpdateList(Arrays.asList(appUpdate.getUpdateDescArray()));
        return getSuccessResponseVO(appUpdateVo);

    }


}
